package br.com.sig.financeiro.frete.presentation.action;

import java.util.ArrayList;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.enterprise.event.ObserverException;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import br.com.sig.criteria.DateCriteriaVisitor;
import br.com.sig.financeiro.frete.business.event.PagarFreteEvent;
import br.com.sig.financeiro.frete.business.model.bo.FreteBO;
import br.com.sig.financeiro.frete.business.model.entity.Frete;
import br.com.sig.presentation.action.BaseListAction;
import br.com.sig.security.BaseIdentity;
import br.com.sig.security.Identity;

@Named
@ViewScoped
public class FreteList extends BaseListAction<Frete> {

	private static final long serialVersionUID = 7603912410855228935L;
	
	private Date dataDeInicio = null;
	private Date dataDeTermino = null;
	private Date dataDePagamento = null;
	
	@Inject
	@Identity
	private BaseIdentity identity;
	
	@Inject
	private FreteBO freteBO;
	
	@PostConstruct
	public void init() {
		setService(freteBO);
		setSortField("data");
	}
	
	@Override
	public void find() {
		this.visitor = new DateCriteriaVisitor("data", dataDeInicio, dataDeTermino);
		super.find();
	}
	
	public boolean enablePayment() {
		if (identity.hasPermission("sig.financeiro.frete.escrita.pagamento") &&
				getSelectedItem() != null && getSelectedItem().getDataDePagamento() == null) {
			return true;
		}
		return false;
	}
	
	public void pagar() {
		
		try {
			beanManager.fireEvent(new PagarFreteEvent(getDataDePagamento(), new ArrayList<Frete>(getSelections())));
			clearSelections();
			setSelectedItem(null);
			messages.info("Pagamento efetuado com sucesso.");			
		} catch (ObserverException e) {			
			messages.error("Falha ao processar o pagamento. Contacte o Administrador do Sistema.");
		} finally {
			setDataDePagamento(null);
		}
		
	}
	
	public Date getDataDeInicio() {
		return dataDeInicio;
	}

	public void setDataDeInicio(Date dataDeInicio) {
		this.dataDeInicio = dataDeInicio;
	}

	public Date getDataDeTermino() {
		return dataDeTermino;
	}

	public void setDataDeTermino(Date dataDeTermino) {
		this.dataDeTermino = dataDeTermino;
	}

	public Date getDataDePagamento() {
		return dataDePagamento;
	}

	public void setDataDePagamento(Date dataDePagamento) {
		this.dataDePagamento = dataDePagamento;
	}
}